const express = require('express');
const router = express.Router();
const Joi = require('joi');
const { Op } = require('sequelize');
const db = require('../../models');
const { authenticateToken } = require('../../middleware/auth');
const { success, error, paginate, validationError, notFound } = require('../../utils/response');

// 输入验证规则
const createDiarySchema = Joi.object({
  title: Joi.string().min(1).max(200).required(),
  content: Joi.string().min(1).required(),
  diary_date: Joi.date().iso().required(),
  category_id: Joi.number().integer().positive().optional(),
  weather: Joi.string().max(20).optional(),
  mood: Joi.string().max(20).optional(),
  is_public: Joi.boolean().optional(),
  tags: Joi.array().items(Joi.number().integer().positive()).optional()
});

const updateDiarySchema = Joi.object({
  title: Joi.string().min(1).max(200).optional(),
  content: Joi.string().min(1).optional(),
  diary_date: Joi.date().iso().optional(),
  category_id: Joi.number().integer().positive().allow(null).optional(),
  weather: Joi.string().max(20).allow('').optional(),
  mood: Joi.string().max(20).allow('').optional(),
  is_public: Joi.boolean().optional(),
  tags: Joi.array().items(Joi.number().integer().positive()).optional()
});

/**
 * 获取日记列表
 * GET /api/diaries
 */
router.get('/', authenticateToken, async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      category_id,
      tag_id,
      keyword,
      start_date,
      end_date,
      weather,
      mood,
      is_public,
      sort = 'diary_date',
      order = 'DESC'
    } = req.query;

    const user_id = req.user.id;
    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);

    // 构建查询条件
    const where = { user_id };

    if (category_id) {
      where.category_id = category_id;
    }

    if (keyword) {
      where[Op.or] = [
        { title: { [Op.like]: `%${keyword}%` } },
        { content: { [Op.like]: `%${keyword}%` } }
      ];
    }

    if (start_date && end_date) {
      where.diary_date = {
        [Op.between]: [start_date, end_date]
      };
    } else if (start_date) {
      where.diary_date = {
        [Op.gte]: start_date
      };
    } else if (end_date) {
      where.diary_date = {
        [Op.lte]: end_date
      };
    }

    if (weather) {
      where.weather = weather;
    }

    if (mood) {
      where.mood = mood;
    }

    if (is_public !== undefined) {
      where.is_public = is_public === 'true';
    }

    // 构建包含关系
    const include = [
      {
        model: db.Category,
        as: 'category',
        attributes: ['id', 'name', 'color', 'icon']
      },
      {
        model: db.Tag,
        as: 'tags',
        attributes: ['id', 'name', 'color'],
        through: { attributes: [] }
      },
      {
        model: db.Image,
        as: 'images',
        attributes: ['id', 'filename', 'original_name', 'file_path', 'width', 'height', 'sort_order']
      }
    ];

    // 如果按标签筛选
    if (tag_id) {
      include.push({
        model: db.Tag,
        as: 'tags',
        where: { id: tag_id },
        attributes: [],
        through: { attributes: [] }
      });
    }

    const { count, rows } = await db.Diary.findAndCountAll({
      where,
      include,
      offset,
      limit,
      order: [[sort, order.toUpperCase()]],
      distinct: true
    });

    return paginate(res, rows, {
      page: parseInt(page),
      pageSize: limit,
      total: count
    });

  } catch (err) {
    console.error('获取日记列表错误:', err);
    return error(res, '获取日记列表失败', 500);
  }
});

/**
 * 搜索日记
 * GET /api/diaries/search
 */
router.get('/search', authenticateToken, async (req, res) => {
  try {
    const {
      keyword = '',
      page = 1,
      limit = 10,
      categoryId,
      tagIds,
      startDate,
      endDate
    } = req.query;

    const user_id = req.user.id;
    const offset = (page - 1) * limit;

    // 构建查询条件
    const where = { user_id };

    // 关键词搜索
    if (keyword.trim()) {
      where[Op.or] = [
        { title: { [Op.like]: `%${keyword}%` } },
        { content: { [Op.like]: `%${keyword}%` } }
      ];
    }

    // 分类筛选
    if (categoryId) {
      where.category_id = categoryId;
    }

    // 日期范围筛选
    if (startDate && endDate) {
      where.diary_date = {
        [Op.between]: [startDate, endDate]
      };
    } else if (startDate) {
      where.diary_date = {
        [Op.gte]: startDate
      };
    } else if (endDate) {
      where.diary_date = {
        [Op.lte]: endDate
      };
    }

    // 构建包含关系
    const include = [
      {
        model: db.Category,
        as: 'category',
        attributes: ['id', 'name', 'color', 'icon']
      },
      {
        model: db.Tag,
        as: 'tags',
        attributes: ['id', 'name', 'color'],
        through: { attributes: [] }
      }
    ];

    // 标签筛选
    if (tagIds) {
      const tagIdArray = Array.isArray(tagIds) ? tagIds : [tagIds];
      include.push({
        model: db.Tag,
        as: 'filterTags',
        where: { id: { [Op.in]: tagIdArray } },
        attributes: [],
        through: { attributes: [] }
      });
    }

    const { count, rows } = await db.Diary.findAndCountAll({
      where,
      include,
      offset,
      limit: parseInt(limit),
      order: [['diary_date', 'DESC']],
      distinct: true
    });

    return paginate(res, rows, {
      page: parseInt(page),
      pageSize: parseInt(limit),
      total: count
    });

  } catch (err) {
    console.error('搜索日记错误:', err);
    return error(res, '搜索日记失败', 500);
  }
});

/**
 * 获取日记详情
 * GET /api/diaries/:id
 */
router.get('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const user_id = req.user.id;

    const diary = await db.Diary.findOne({
      where: { id, user_id },
      include: [
        {
          model: db.Category,
          as: 'category',
          attributes: ['id', 'name', 'color', 'icon']
        },
        {
          model: db.Tag,
          as: 'tags',
          attributes: ['id', 'name', 'color'],
          through: { attributes: [] }
        },
        {
          model: db.Image,
          as: 'images',
          attributes: ['id', 'filename', 'original_name', 'file_path', 'width', 'height', 'sort_order'],
          order: [['sort_order', 'ASC']]
        }
      ]
    });

    if (!diary) {
      return notFound(res, '日记不存在');
    }

    // 增加浏览次数
    await diary.incrementViewCount();

    return success(res, diary);

  } catch (err) {
    console.error('获取日记详情错误:', err);
    return error(res, '获取日记详情失败', 500);
  }
});

/**
 * 获取日历数据
 * GET /api/diaries/calendar
 */
router.get('/calendar', authenticateToken, async (req, res) => {
  try {
    const { year, month } = req.query;
    const user_id = req.user.id;
    
    const targetYear = year ? parseInt(year) : new Date().getFullYear();
    const targetMonth = month ? parseInt(month) - 1 : new Date().getMonth();
    
    const startDate = new Date(targetYear, targetMonth, 1);
    const endDate = new Date(targetYear, targetMonth + 1, 0);

    const calendarData = await db.Diary.findAll({
      where: {
        user_id,
        diary_date: {
          [Op.between]: [startDate, endDate]
        }
      },
      attributes: [
        [db.sequelize.fn('DATE', db.sequelize.col('diary_date')), 'date'],
        [db.sequelize.fn('COUNT', db.sequelize.col('id')), 'count']
      ],
      group: [db.sequelize.fn('DATE', db.sequelize.col('diary_date'))],
      order: [[db.sequelize.fn('DATE', db.sequelize.col('diary_date')), 'ASC']]
    });

    return success(res, {
      year: targetYear,
      month: targetMonth + 1,
      calendar: calendarData.map(item => ({
        date: item.getDataValue('date'),
        count: parseInt(item.getDataValue('count'))
      }))
    });

  } catch (err) {
    console.error('获取日历数据错误:', err);
    return error(res, '获取日历数据失败', 500);
  }
});

/**
 * 按日期获取日记
 * GET /api/diaries/by-date
 */
router.get('/by-date', authenticateToken, async (req, res) => {
  try {
    const { date } = req.query;
    const user_id = req.user.id;

    if (!date) {
      return validationError(res, '请提供日期参数');
    }

    const diaries = await db.Diary.findAll({
      where: {
        user_id,
        diary_date: date
      },
      include: [
        {
          model: db.Category,
          as: 'category',
          attributes: ['id', 'name', 'color', 'icon']
        },
        {
          model: db.Tag,
          as: 'tags',
          attributes: ['id', 'name', 'color'],
          through: { attributes: [] }
        },
        {
          model: db.Image,
          as: 'images',
          attributes: ['id', 'filename', 'original_name', 'width', 'height'],
          order: [['sort_order', 'ASC']]
        }
      ],
      order: [['created_at', 'DESC']]
    });

    return success(res, diaries);

  } catch (err) {
    console.error('按日期获取日记错误:', err);
    return error(res, '获取日记失败', 500);
  }
});

/**
 * 创建日记
 * POST /api/diaries
 */
router.post('/', authenticateToken, async (req, res) => {
  try {
    // 输入验证
    const { error: validationErr, value } = createDiarySchema.validate(req.body);
    if (validationErr) {
      return validationError(res, '输入数据不合法', validationErr.details[0].message);
    }

    const user_id = req.user.id;
    const { tags, ...diaryData } = value;

    // 检查分类是否属于当前用户
    if (diaryData.category_id) {
      const category = await db.Category.findOne({
        where: { id: diaryData.category_id, user_id }
      });
      if (!category) {
        return error(res, '分类不存在或不属于当前用户', 400);
      }
    }

    // 检查标签是否属于当前用户
    if (tags && tags.length > 0) {
      const tagCount = await db.Tag.count({
        where: { id: { [Op.in]: tags }, user_id }
      });
      if (tagCount !== tags.length) {
        return error(res, '部分标签不存在或不属于当前用户', 400);
      }
    }

    // 创建日记
    const diary = await db.Diary.create({
      ...diaryData,
      user_id
    });

    // 关联标签
    if (tags && tags.length > 0) {
      await diary.setTags(tags);
    }

    // 获取完整的日记信息
    const createdDiary = await db.Diary.findByPk(diary.id, {
      include: [
        {
          model: db.Category,
          as: 'category',
          attributes: ['id', 'name', 'color', 'icon']
        },
        {
          model: db.Tag,
          as: 'tags',
          attributes: ['id', 'name', 'color'],
          through: { attributes: [] }
        }
      ]
    });

    return success(res, createdDiary, '日记创建成功', 200);

  } catch (err) {
    console.error('创建日记错误:', err);
    return error(res, '创建日记失败', 500);
  }
});

/**
 * 更新日记
 * PUT /api/diaries/:id
 */
router.put('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const user_id = req.user.id;

    // 输入验证
    const { error: validationErr, value } = updateDiarySchema.validate(req.body);
    if (validationErr) {
      return validationError(res, '输入数据不合法', validationErr.details[0].message);
    }

    const { tags, ...diaryData } = value;

    // 查找日记
    const diary = await db.Diary.findOne({
      where: { id, user_id }
    });

    if (!diary) {
      return notFound(res, '日记不存在');
    }

    // 检查分类是否属于当前用户
    if (diaryData.category_id) {
      const category = await db.Category.findOne({
        where: { id: diaryData.category_id, user_id }
      });
      if (!category) {
        return error(res, '分类不存在或不属于当前用户', 400);
      }
    }

    // 检查标签是否属于当前用户
    if (tags && tags.length > 0) {
      const tagCount = await db.Tag.count({
        where: { id: { [Op.in]: tags }, user_id }
      });
      if (tagCount !== tags.length) {
        return error(res, '部分标签不存在或不属于当前用户', 400);
      }
    }

    // 更新日记
    await diary.update(diaryData);

    // 更新标签关联
    if (tags !== undefined) {
      await diary.setTags(tags);
    }

    // 获取更新后的日记信息
    const updatedDiary = await db.Diary.findByPk(diary.id, {
      include: [
        {
          model: db.Category,
          as: 'category',
          attributes: ['id', 'name', 'color', 'icon']
        },
        {
          model: db.Tag,
          as: 'tags',
          attributes: ['id', 'name', 'color'],
          through: { attributes: [] }
        }
      ]
    });

    return success(res, updatedDiary, '日记更新成功');

  } catch (err) {
    console.error('更新日记错误:', err);
    return error(res, '更新日记失败', 500);
  }
});

/**
 * 删除日记
 * DELETE /api/diaries/:id
 */
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const user_id = req.user.id;

    const diary = await db.Diary.findOne({
      where: { id, user_id }
    });

    if (!diary) {
      return notFound(res, '日记不存在');
    }

    await diary.destroy();

    return success(res, null, '日记删除成功');

  } catch (err) {
    console.error('删除日记错误:', err);
    return error(res, '删除日记失败', 500);
  }
});

module.exports = router; 